import Link from 'next/link';
import { Heart } from 'lucide-react';
import { formatDate } from '@/lib/utils/format';
import { UserCommentRow, UserProfileDto } from '@/types/account/profile';

type Props = {
	list: UserCommentRow[];
	author?: UserProfileDto|null;
};

export default function UserCommentsList({ list, author }: Props)
{
	if (list.length === 0) {
		return <p className="user-profile__empty">작성한 댓글이 없습니다.</p>;
	}

	const authorDisplay = author?.name || author?.memberSID || null;
	const avatarInitial = (authorDisplay?.charAt(0) || '?').toUpperCase();

	return (
		<ul className="user-profile__list">
			{list.map((row) => (
				<li key={row.commentID} className="user-profile__list-item">
					<Link href={`/post/${row.postID}`} className="user-profile__list-link">
						<div className="user-profile__list-body">
							{author && (
								<header className="user-profile__list-author">
									{author.thumb ? (
										<img src={author.thumb} alt={authorDisplay ?? ''} className="user-profile__list-author-avatar" />
									) : (
										<span className="user-profile__list-author-avatar user-profile__list-author-avatar--fallback">{avatarInitial}</span>
									)}
									<span className="user-profile__list-author-name">{authorDisplay}</span>
									<span className="user-profile__list-author-handle">@{author.memberSID}</span>
									<span className="user-profile__list-time">· {formatDate(row.createdAt)}</span>
								</header>
							)}

							<p className="user-profile__list-comment">{stripTags(row.content)}</p>

							<div className="user-profile__list-parent">
								<span className="user-profile__list-board">{row.boardName}</span>
								<span className="user-profile__list-parent-subject">→ {row.postSubject}</span>
							</div>

							<div className="user-profile__list-stats">
								<span className="user-profile__list-stat" title="좋아요">
									<Heart size={14} strokeWidth={1.75} />
									{row.likes.toLocaleString()}
								</span>
							</div>
						</div>
					</Link>
				</li>
			))}
		</ul>
	);
}

function stripTags(html: string): string {
	return html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200);
}